<template>
    <div class="danmaku-container">
      <div class="danmaku-track">
        <div 
          v-for="(item, index) in activeDanmaku" 
          :key="index"
          class="danmaku-item"
          :style="{ 
            animationDuration: `${item.duration}s`,
            animationDelay: `${item.delay}s`,
            color: item.color
          }"
        >
          {{ item.text }}
        </div>
      </div>
    </div>
  </template>
  
  <script setup>
  import { ref, onMounted, onUnmounted } from 'vue';
  
  const props = defineProps({
    messages: {
      type: Array,
      default: () => []
    },
    autoplay: {
      type: Boolean,
      default: true
    }
  });
  
  const defaultDanmaku = [
    "欢迎使用云存储分享功能，轻松传递精彩内容！"  
];
  
  const activeDanmaku = ref([]);
  let danmakuTimer = null;
  
  const getRandomColor = () => {
    const colors = [
      '#3498db', '#2ecc71', '#9b59b6', '#e74c3c', '#f39c12',
      '#1abc9c', '#d35400', '#c0392b', '#16a085', '#8e44ad'
    ];
    return colors[Math.floor(Math.random() * colors.length)];
  };
  
  const addDanmaku = () => {
    const messages = props.messages.length ? props.messages : defaultDanmaku;
    const randomIndex = Math.floor(Math.random() * messages.length);
    const text = messages[randomIndex];
    
    activeDanmaku.value.push({
      text,
      duration: 10 + Math.random() * 5,
      delay: 0,
      color: getRandomColor()
    });
    
    if (activeDanmaku.value.length > 10) {
      activeDanmaku.value.shift();
    }
  };
  
  const startDanmaku = () => {
    if (danmakuTimer) {
      clearInterval(danmakuTimer);
    }
    
    addDanmaku();
    
    danmakuTimer = setInterval(() => {
      addDanmaku();
    }, 2000 + Math.random() * 2000);
  };
  
  const stopDanmaku = () => {
    if (danmakuTimer) {
      clearInterval(danmakuTimer);
      danmakuTimer = null;
    }
  };
  
  defineExpose({
    start: startDanmaku,
    stop: stopDanmaku
  });
  
  onMounted(() => {
    if (props.autoplay) {
      startDanmaku();
    }
  });
  
  onUnmounted(() => {
    stopDanmaku();
  });
  </script>
  
  <style scoped>
  .danmaku-container {
    width: 100%;
    height: 38px;
    overflow: hidden;
    position: relative;
    margin: 8px 0;
    background-color: rgba(0, 0, 0, 0.02);
    border-radius: 6px;
    box-shadow: inset 0 0 2px rgba(0, 0, 0, 0.05);
  }
  
  .danmaku-track {
    width: 100%;
    height: 100%;
    position: relative;
  }
  
  .danmaku-item {
    position: absolute;
    white-space: nowrap;
    left: 100%;
    top: 50%;
    transform: translateY(-50%);
    animation: danmaku-scroll linear forwards;
    font-size: 16px;
    opacity: 0.85;
    padding: 3px 6px;
    border-radius: 4px;
    background-color: rgba(0, 0, 0, 0.05);
    text-shadow: 0 1px 1px rgba(255, 255, 255, 0.5);
  }
  
  @keyframes danmaku-scroll {
    from {
      left: 100%;
    }
    to {
      left: -100%;
    }
  }
  </style>